package controllers.commands
{
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	import flash.utils.setTimeout;
	
	import controllers.commands.base.BaseCommand;
	
	import exception.ExceptionUtil;
	import exception.code.ErrorCode;
	
	import model.protocal.GoogleGLMParseProtocol;
	import model.protocal.base.IProtocol;
	
	import utils.BytesUtil;
	
	/***
	 *  执行转换移动数据 
	 *  @Time: 2012 10:08:37 PM 
	 **/ 
	public class ParseMobileInfoCommand extends BaseCommand
	{
		private var protocal:IProtocol;
		private var socket:Socket ;
		private var cwsIP:String = "203.156.231.38";
		private var googleIP:String = "74.125.128.105";
		private var cwsPrefix:String = "/gpsn.php";
		private var googlePrefix:String = "/glm/mmap";
		
		public function ParseMobileInfoCommand(protocol:IProtocol)
		{
			super();
			this.protocal = protocol;
			if ( this.protocal == null )
			{
				ExceptionUtil.handleException(ErrorCode.BAD_MOBILE_CODE);
			}
		}
		
		/**
		 * 输出二进制流
		 */
		private function hex2BytesArray(str:String):ByteArray {
			var len:int = str.length/2;
			var re:String = "";
			var outBytesArray:ByteArray = new ByteArray();
			outBytesArray.endian = Endian.LITTLE_ENDIAN;
			for(var ii:int=0; ii<len;ii++) {
				var pos:int = ii*2;
				var tempStr:String = String.fromCharCode(parseInt(str.substr(pos,2), 16));
				re += tempStr;
			}
			outBytesArray.writeUTFBytes(re);
			return outBytesArray;
		}		
		
		/**
		 * 重新生成二进制数据流
		 */
		private function hex2BytesM2( cellTowerId : int, 
											mobileCountryCode:int, 
									 		mobileNetworkCode:int, 
											locationAreaCode:int):Array {
			var pd : Array = new Array();
			//长度必须为55位
			pd[1] = 14;     //0x0e;
			pd[16] = 27;    //0x1b;
			pd[47] = 255;   //0xff;
			pd[48] = 255;   //0xff;
			pd[49] = 255;   //0xff;
			pd[50] = 255;   //0xff;
			pd.length = 55;
			// GSM uses 4 digits while UTMS used 6 digits (hex)
			//pd[28] = ((Int64)cellTowerId > 65536) ? int(5) : int(3); 
			pd[28] = 3;
			
			Shift(pd, 17, mobileNetworkCode);
			Shift(pd, 21, mobileCountryCode);
			Shift(pd, 31, cellTowerId);
			Shift(pd, 35, locationAreaCode);
			Shift(pd, 39, mobileNetworkCode);
			Shift(pd, 43, mobileCountryCode);
			return pd;
		}
		
		/**
		 * 移位
		 */
		private static function Shift(data:Array, startIndex:int, leftOperand:int):void
		{
			var rightOperand : int = 24;
			
			for (var i : int = 0; i < 4; i++, rightOperand -= 8)
			{
				data[startIndex++] = int((leftOperand >> rightOperand) & 255);
			}
		}
		
		private function sendByProtocal():void{
		
		}
		
		private function sendByLoader():void{
			var g2Url:String = this.protocal.getProtocalString();
			var urlRequest:URLRequest = new URLRequest( g2Url );
			urlRequest.contentType="multipart/form-data";							

			var loader:URLLoader = new URLLoader(urlRequest);		
			loader.addEventListener(ProgressEvent.PROGRESS, onProgressHandler);
			loader.addEventListener(Event.COMPLETE, this.protocal.onResponseHandler);
			
			var startTime:Number = new Date().milliseconds;
			loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, function(evt:HTTPStatusEvent):void{
				trace("返回状态 :" +evt.status + " 花费时间:" + (new Date().milliseconds-startTime));
			});	
			loader.addEventListener(IOErrorEvent.IO_ERROR, function(evt:IOErrorEvent):void{
				trace("ioError!!!" + evt.text) ;
			});
			loader.load(urlRequest);
		}
		
		private function sendBySocket():void{
			socket = new Socket();
			socket.addEventListener(Event.CONNECT, function(evt:Event):void{
				trace("连接GLM服务器成功!");
			});
			socket.addEventListener(ProgressEvent.SOCKET_DATA, onDataHandler);			
			socket.addEventListener(IOErrorEvent.IO_ERROR, function(evt:IOErrorEvent):void{
				trace("连接错误:" + evt.text);
			});
			socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function(evt:SecurityErrorEvent):void{
				trace("安全错误:" + evt.text);
			});
				
			socket.connect("localhost", 8087);
		}
		
		private function onDataHandler(evt:ProgressEvent):void{
			trace(" data: " + evt.bytesLoaded + " / " + evt.bytesTotal);
		}
		/**
		 * 执行 
		 */
		public override function execute():void {
			sendByLoader();
		}
	
		
		private function onProgressHandler(evt:ProgressEvent):void
		{
			trace("当前:" + evt.bytesLoaded + " / " + evt.bytesTotal);
		}
	}
}